package com.xxx.mall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.bo.AuthAccountBO;
import com.xxx.mall.constant.EnableStatusEnum;
import com.xxx.mall.constant.InputUserNameEnum;
import com.xxx.mall.exception.MallException;
import com.xxx.mall.mapper.AuthAccountMapper;
import com.xxx.mall.model.AuthAccount;
import com.xxx.mall.response.ResponseEnum;
import com.xxx.mall.service.AuthAccountService;
import com.xxx.mall.util.PrincipalUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 统一账户信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-15
 */
@Service
public class AuthAccountServiceImpl extends ServiceImpl<AuthAccountMapper, AuthAccount> implements AuthAccountService {

    @Resource
    PasswordEncoder passwordEncoder;

    @Override
    public AuthAccountBO getInfoByUserNameAndPassword(String username, String password, Integer sysType) {
        InputUserNameEnum inputUserNameEnum = null;
        if (PrincipalUtil.isUserName(username)) {
            inputUserNameEnum = InputUserNameEnum.USERNAME;
        }
        if (inputUserNameEnum == null) {
            throw new MallException("请输入正确的用户名");
        }
        AuthAccount authAccount = baseMapper.getAuthAccountByUserName(inputUserNameEnum.value, username, sysType);
        // 用户不存在
        if (authAccount == null) {
            throw new MallException(ResponseEnum.LOGIN_ERROR);
        }
        // 用户被禁用
        if (EnableStatusEnum.DISABLE.value().equals(authAccount.getStatus())) {
            throw new MallException(ResponseEnum.ACCOUNT_LOCKED);
        }
        // 密码错误
        if (!passwordEncoder.matches(password, authAccount.getPassword())) {
            throw new MallException(ResponseEnum.LOGIN_ERROR);
        }
        //todo 使用第三方转换工具
        AuthAccountBO accountBO = new AuthAccountBO();
        accountBO.setUid(authAccount.getUid());
        accountBO.setUsername(authAccount.getUsername());
        accountBO.setSysType(authAccount.getSysType());
        accountBO.setUserId(authAccount.getUserId());
        accountBO.setTenantId(authAccount.getTenantId());
        return accountBO;
    }
}
